package org.jeecg.modules.ZcglJiecun.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.ZcglJiecun.entity.ZcglJiecun;
import org.jeecg.modules.ZcglJiecun.service.IZcglJiecunService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.putstorage.entity.ZcglPutStorageAssets;
import org.jeecg.modules.putstorage.service.IZcglPutStorageAssetsService;
import org.jeecg.modules.zcgl.entity.AssetFixed;
import org.jeecg.modules.zcgl.entity.AssetFixedCategory;
import org.jeecg.modules.zcgl.service.IAssetFixedCategoryService;
import org.jeecg.modules.zcgl.service.IAssetFixedService;
import org.jeecg.modules.zcglRecipients.entity.ZcglRecipientsAssets;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 结存报表
 * @Author: jeecg-boot
 * @Date:   2023-12-29
 * @Version: V1.0
 */
@Api(tags="结存报表")
@RestController
@RequestMapping("/ZcglJiecun/zcglJiecun")
@Slf4j
public class ZcglJiecunController extends JeecgController<ZcglJiecun, IZcglJiecunService> {
	@Autowired
	private IZcglJiecunService zcglJiecunService;

	 @Autowired
	 private IAssetFixedService assetFixedServiceImpl;
	 @Autowired
	 private IAssetFixedCategoryService assetFixedCategoryServiceImpl;

	 @Autowired
	 private IZcglJiecunService zcglJiecunServiceImpl;

	 @Autowired
	 private IZcglPutStorageAssetsService zcglPutStorageAssetsServiceImpl;

	 public static void main(String[] args) {
		 // 输入的日期字符串
		 String dateString = "2023-12";

		 // 定义日期格式
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

		 // 解析日期字符串
		 YearMonth yearMonth = YearMonth.parse(dateString, formatter);

		 // 减去一个月
		 YearMonth lastMonth = yearMonth.minusMonths(1);

		 // 输出上一个月的年和月份
		 int lastYear = lastMonth.getYear();
		 int lastMonthNumber = lastMonth.getMonthValue();

		 // 输出结果
		 System.out.println("上一个月的年月是：" + lastYear + "-" + String.format("%02d", lastMonthNumber));
	 }
	 /**
	  * 分页列表查询
	  *

	  * @return
	  */
	 @AutoLog(value = "结存报表-分页列表查询")
	 @ApiOperation(value="结存报表-分页列表查询", notes="结存报表-分页列表查询")
	 @GetMapping(value = "/jiechun")
	 public Result<?> jiechun(@RequestParam(value = "time")String time) {
		 // 输入的日期字符串
		 String dateString = "2023-12";
		 // 定义日期格式
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
		 // 解析日期字符串
		 YearMonth yearMonth = YearMonth.parse(time, formatter);
		 // 减去一个月
		 YearMonth lastMonth1 = yearMonth.minusMonths(1);

		 // 输出上一个月的年和月份
		 int lastYear = lastMonth1.getYear();
		 int lastMonthNumber = lastMonth1.getMonthValue();
		 String shangyue = lastYear + "-" + String.format("%02d", lastMonthNumber);



		 List<AssetFixedCategory> assetFixedList = assetFixedCategoryServiceImpl.list();

		 for (int a = 0; a < assetFixedList.size(); a++) {
			 String ckId = assetFixedList.get(a).getId();
			 String ckName = assetFixedList.get(a).getName();
			 //首先循环所有的物资 对每1个物资进行处理。
			 List<AssetFixed> list = assetFixedServiceImpl.list();
			 for (int i = 0; i < list.size(); i++) {
				 //获取每个物资
				 AssetFixed assetFixed = list.get(i);
				 System.out.println(assetFixed+"我是什么");
				 System.out.println(assetFixed.getPrice()+"单我是什么价");
				 Date date = new Date();
				 Date currentDate = new Date();
				 SimpleDateFormat sdf = new SimpleDateFormat("MM");
				 String lastMonthStr = sdf.format(currentDate);
				 int lastMonth = Integer.parseInt(lastMonthStr) - 1;
				 if (lastMonth == 0) {
					 lastMonth = 12;
				 }

				 Calendar calendar = Calendar.getInstance();
				 calendar.add(Calendar.MONTH, -1); // 减去一个月
				 int year = calendar.get(Calendar.YEAR); // 获取年份
				 System.out.println(year);
//            String timew = year+"-"+lastMonth;
				 String timew = time;
				 System.out.println(timew+"当前日期11"+assetFixed.getCode());
				 System.out.println(shangyue+"当前日期11111"+assetFixed.getCode());

				 //去获取上个月的结存单价和结存数量

				 ZcglJiecun zcglJiecun = zcglJiecunServiceImpl.getOne(new QueryWrapper<ZcglJiecun>().eq("time",timew).eq("asset_code",assetFixed.getCode()).eq("ck_id",ckId));
				 System.out.println(zcglJiecun+"低价");
				 ZcglJiecun shangyuejiecun = zcglJiecunServiceImpl.getOne(new QueryWrapper<ZcglJiecun>().eq("time",shangyue).eq("asset_code",assetFixed.getCode()).eq("ck_id",ckId));



				 if (zcglJiecun == null) {
					 System.out.println(assetFixed.getPrice()+"");
					 //上月结存数量
					 Double count = 0.0;
					 //上月结存单价
					 Double price = 0.0;
					 if(shangyuejiecun!=null){
						 count = shangyuejiecun.getCount();
//						 price = zcglJiecun.getPrice();
					 }
					 BigDecimal total = new BigDecimal(0.0);
					 BigDecimal lCount = new BigDecimal(0.0);
					 BigDecimal lyCount = new BigDecimal(0.0);
					 List<ZcglPutStorageAssets> list1 = zcglJiecunServiceImpl.getRkList(assetFixed.getCode(),timew,ckId);
					 for (int j = 0; j < list1.size(); j++) {

						 //本月入库金额
						 total =  list1.get(j).getAssetPrice().multiply(list1.get(j).getAssetAmount()).add(total);

						 //本月入库数量
						 lCount = list1.get(j).getAssetAmount().add(lCount);
					 }

					 List<ZcglRecipientsAssets> list2 = zcglJiecunServiceImpl.getListByCk(assetFixed.getCode(),ckId,timew);
					 for (int v = 0; v < list2.size(); v++) {
						 //本月领用数量
						 lyCount = list2.get(v).getAssetAmount().add(lyCount);
					 }
					 Double benyuekucun = count.doubleValue()+lCount.doubleValue()-lyCount.doubleValue();
					 System.out.println("本月结存是多少"+benyuekucun);
					 Double jiecundanjia = 0.0;
//					 if(benyuekucun==0){
//						 jiecundanjia = 0.0;
//
//					 }else{
//						 jiecundanjia = ((price*count)+total.doubleValue())/benyuekucun;
						AssetFixed assetFixed1 = assetFixedServiceImpl.getOne(new QueryWrapper<AssetFixed>().eq("asset_fixed_category_id",ckId).eq("code",assetFixed.getCode()));
						if(assetFixed1!=null){
//							benyuekucun = assetFixed1.getAmount().doubleValue();
							jiecundanjia = assetFixed1.getPrice().doubleValue();

						}

//					 }

					 ZcglJiecun zcglJiecun1 = new ZcglJiecun();
					 zcglJiecun1.setAssetCode(assetFixed.getCode());
					 zcglJiecun1.setAssetName(assetFixed.getName());
					 zcglJiecun1.setRkCount(lCount.doubleValue());
					 zcglJiecun1.setCkCount(lyCount.doubleValue());
					 zcglJiecun1.setAssetId(assetFixed.getId());
					 zcglJiecun1.setTime(timew);
					 DecimalFormat df = new DecimalFormat("#.00");

					 zcglJiecun1.setPrice(Double.parseDouble(df.format(jiecundanjia)));
					 zcglJiecun1.setCount(benyuekucun);
					 zcglJiecun1.setCkId(ckId);
					 zcglJiecun1.setCk(ckName);
					 zcglJiecun1.setType("2");

					 if(shangyuejiecun!=null){

						 zcglJiecun1.setShangyueJiecun(shangyuejiecun.getCount());
					 }else{
						 zcglJiecun1.setShangyueJiecun(0.0);

					 }
					 System.out.println(zcglJiecun1);
					 if(zcglJiecun1.getRkCount()!=0 ||
							 zcglJiecun1.getCkCount()!=0 ||
							 zcglJiecun1.getShangyueJiecun()!=0
					 ){
						 zcglJiecunServiceImpl.save(zcglJiecun1);
					 }

				 }

			 }



		 }




		 return Result.ok("完成");
	 }


	/**
	 * 分页列表查询
	 *
	 * @param zcglJiecun
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "结存报表-分页列表查询")
	@ApiOperation(value="结存报表-分页列表查询", notes="结存报表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZcglJiecun zcglJiecun,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZcglJiecun> queryWrapper = QueryGenerator.initQueryWrapper(zcglJiecun, req.getParameterMap());
		Page<ZcglJiecun> page = new Page<ZcglJiecun>(pageNo, pageSize);
		IPage<ZcglJiecun> pageList = zcglJiecunService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param zcglJiecun
	 * @return
	 */
	@AutoLog(value = "结存报表-添加")
	@ApiOperation(value="结存报表-添加", notes="结存报表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZcglJiecun zcglJiecun) {
		zcglJiecunService.save(zcglJiecun);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param zcglJiecun
	 * @return
	 */
	@AutoLog(value = "结存报表-编辑")
	@ApiOperation(value="结存报表-编辑", notes="结存报表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ZcglJiecun zcglJiecun) {
		zcglJiecunService.updateById(zcglJiecun);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "结存报表-通过id删除")
	@ApiOperation(value="结存报表-通过id删除", notes="结存报表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		zcglJiecunService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "结存报表-批量删除")
	@ApiOperation(value="结存报表-批量删除", notes="结存报表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zcglJiecunService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "结存报表-通过id查询")
	@ApiOperation(value="结存报表-通过id查询", notes="结存报表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ZcglJiecun zcglJiecun = zcglJiecunService.getById(id);
		if(zcglJiecun==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(zcglJiecun);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param zcglJiecun
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZcglJiecun zcglJiecun) {
        return super.exportXls(request, zcglJiecun, ZcglJiecun.class, "结存报表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZcglJiecun.class);
    }

}
